package cn.gs.global.server.account;

// @author gs
import cn.gs.db.BoolTransaction;
import cn.gs.db.HibernateUtil;
import cn.gs.global.common.timer.ITimerListener;
import cn.gs.global.table.account.SimOgn;
import cn.gs.util.set.Cache;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import org.hibernate.Query;

public class TimerListenerImpl implements ITimerListener {

    AccountCore core;
    HibernateUtil util;
    int date;

    public TimerListenerImpl(AccountCore core) {
        this.core = core;
        this.util = core.getUtil();
    }

    @Override
    public void onNewYear(int year) {
    }

    @Override
    public void onNewMonth(int month) {
    }

    @Override
    public void onNewDay(int date) {
        this.date = date;
        util.transaction(new BoolTransaction() {

            @Override
            public boolean work() throws RuntimeException {

                Query q = util.query("from SimOgn where lastcheck<:month");
                q.setParameter("month", TimerListenerImpl.this.date / 30);
                List<SimOgn> list = q.list();
                accountQueue.clear();
                accountQueue.addAll(list);

                return true;
            }
        });
    }
    Queue<SimOgn> accountQueue = new LinkedList<>();

    @Override
    public void onHeartbeat(int date) {
        this.date = date;
        for (int i = 0; i < CAccountSetting.ACCOUNT_PER_HEART; ++i) {
            SimOgn ogn = accountQueue.poll();
            if (null != ogn && ogn.getId() > 0) {
                MonthAccount ac = core.create(ogn);
                core.getPool().execute(ac);
            }
        }
    }
}
